package app

import (
	"os/exec"

	"gitee.com/extrame/fb-runner/util"
	"github.com/sirupsen/logrus"
)

func Invoke(base string, c *Chaincode, user_args []string) error {

	var orderer = util.Config.GetOrdererOrganization()
	var args = []string{
		"chaincode", "invoke",
		"--channelID", c.Channel, "--name", c.Name,
	}
	args = append(args, orderer.GetConnArgs(base)...)
	cmd := exec.Command("peer", args...)
	var has = false
	for _, org := range util.Config.GetPeerOrganizations() {
		if !has {
			util.UseOrg(cmd, base, org, true)
		}
		p, err := org.GetLocalPeer(true)
		if err != nil {
			return err
		}
		cmd.Args = append(cmd.Args,
			"--peerAddresses", p.GetUrl(),
			"--tlsRootCertFiles", p.GetTlsCaPath(base))
	}
	cmd.Args = append(cmd.Args, user_args...)
	std, _, err := util.Run(cmd)
	logrus.Info("exec finished with " + std)
	if err != nil {
		return err
	}
	return nil
}
